// Users.hpp
#pragma once

#include <iostream>
#include <pthread.h>
#include <unordered_set>
#include <string>
#include <fstream>
#include <cassert>
#include <memory>
#include <jsoncpp/json/json.h>
#include "../comm/mysqlManager.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"

namespace ns_users
{
    using std::string;
    // const string users_list = "./users/users.list";
    const string image_path = "../resource/image/";
    using namespace ns_util;
    using namespace ns_log;

    class Users
    {
    private:
        std::unordered_set<int> _admins;
        std::unordered_set<int> _users;

        pthread_mutex_t _mutex;
        MySQLManager dbManager;

    public:
        Users(const std::string &host, const std::string &user, const std::string &password, const std::string &dbName) {
            LOG(DEBUG) << host << " " << user << " " << password << " " << dbName << std::endl;
            pthread_mutex_init(&_mutex, nullptr);
            if (!dbManager.openDatabase(host, user, password, dbName))
            {
                LOG(ERROR) << "无法打开数据库 " << dbManager.getErrorMessage() << std::endl;
            }
            LOG(DEBUG) << "初始化用户管理器" << std::endl;
        }

        ~Users() {
            pthread_mutex_destroy(&_mutex);
            dbManager.closeDatabase();
        }

        // 判断用户是否存在
        bool isUserExist(const std::string &username) {
            std::string query = "SELECT username FROM user_tb WHERE username = '" + username + "';";
            auto results = dbManager.executeSelect(query);

            return !results.empty() && !results[0].empty();
        }

        // 注销函数
        bool logoff(const std::string &username) {
            std::string query = "SELECT username FROM user_tb WHERE username = '" + username + "';";
            auto results = dbManager.executeSelect(query);

            if (!results.empty() && results[0].size() >= 1) {
                query = "DELETE FROM user_tb WHERE username = '" + username + "';";
                dbManager.executeQuery(query);
                LOG(DEBUG) << "注销成功，用户: " << username << std::endl;
                return true;
            } else {
                LOG(DEBUG) << "注销失败，用户不存在: " << username << std::endl;
                return false;
            }
        }

        // 登录函数
        bool login(const std::string &username, const std::string &password, const std::string &email) {
            std::string query = "SELECT password, email FROM user_tb WHERE username = '" + username + "';";
            auto results = dbManager.executeSelect(query);

            if (!results.empty() && results[0].size() >= 2) {
                std::string storedPassword = results[0][0];
                std::string storedEmail = results[0][1];
                // LOG(INFO) << "数据库信息: " << "密码: " << storedPassword << " " << "电子邮件:" << storedEmail << std::endl;

                if (storedPassword == password && storedEmail == email) {
                    LOG(DEBUG) << "登录成功" << std::endl;
                    return true;
                } else {
                    LOG(DEBUG) << "登录失败, 信息不匹配" << std::endl;
                    return false;
                }
            } else {
                LOG(DEBUG) << "登录失败, 用户不存在" << std::endl;
                return false;
            }
        }

        // 注册用户函数
        bool registerUser(const std::string &username, const std::string &password, const std::string &email, std::string &resp) {
            // LOG(DEBUG) << "开始注册用户" << std::endl;
            std::string checkUsernameQuery = "SELECT 1 FROM user_tb WHERE username = '" + username + "';";
            auto usernameResults = dbManager.executeSelect(checkUsernameQuery);

            if (!usernameResults.empty()) {
                resp = "注册失败，用户名已存在";
                return false;
            }

            std::string checkEmailQuery = "SELECT 1 FROM user_tb WHERE email = '" + email + "';";
            auto emailResults = dbManager.executeSelect(checkEmailQuery);

            if (!emailResults.empty()) {
                resp = "注册失败，邮箱已存在";
                return false;
            }

            std::string insertQuery = "INSERT INTO user_tb (username, password, email) VALUES ('" + username + "', '" + password + "', '" + email + "');";
            bool success = dbManager.executeQuery(insertQuery);

            if (success) {
                LOG(INFO) << "注册用户成功" << std::endl;
                resp = "注册成功";
                return true;
            } else {
                resp = "注册失败，数据库错误";
                return false;
            }
        }

        // 获取用户信息
        Json::Value getUserInfo(const std::string &username) {
            // LOG(DEBUG) << "getUserInfo代码执行" << "\n";
            Json::Value userInfo;

            std::string query = "SELECT * FROM user_tb WHERE username = '" + username + "';";
            auto results = dbManager.executeSelect(query);
            std::string errMsg = dbManager.getErrorMessage();

            if (!errMsg.empty()) {
                LOG(ERROR) << "查询用户信息失败: " << errMsg << std::endl;
                userInfo["error"] = errMsg;
                return userInfo;
            }

            if (!results.empty() && !results[0].empty()) {
                userInfo["id"] = results[0][0];
                userInfo["username"] = results[0][1];
                userInfo["email"] = results[0][3];
                userInfo["phone"] = results[0][4];
                userInfo["gender"] = results[0][5];
                userInfo["description"] = results[0][6];
                userInfo["avatarUrl"] = results[0][7];
            } else {
                userInfo["error"] = "用户不存在";
            }

            return userInfo;
        }

        // 更新用户信息
        bool updateUserInfo(const std::string &username, const Json::Value &newInfo, std::string &resp) {
            // LOG(DEBUG) << "updateUserInfo代码执行" << "\n";
            
            Json::Value userInfo = getUserInfo(username);
            if (userInfo.isMember("error")) {
                resp = userInfo["error"].asString();
                return false;
            }

            std::string updateQuery = "UPDATE user_tb SET ";
            bool first = true;

            if (newInfo.isMember("password")) {
                updateQuery += "password = '" + newInfo["password"].asString() + "'";
                first = false;
            }
            if (newInfo.isMember("email")) {
                if (!first) updateQuery += ", ";
                updateQuery += "email = '" + newInfo["email"].asString() + "'";
                first = false;
            }
            if (newInfo.isMember("phone")) {
                if (!first) updateQuery += ", ";
                updateQuery += "phone = '" + newInfo["phone"].asString() + "'";
                first = false;
            }
            if (newInfo.isMember("gender")) {
                if (!first) updateQuery += ", ";
                updateQuery += "gender = '" + newInfo["gender"].asString() + "'";
                first = false;
            }
            if (newInfo.isMember("description")) {
                if (!first) updateQuery += ", ";
                updateQuery += "description = '" + newInfo["description"].asString() + "'";
            }
            if (newInfo.isMember("avatar")) {
                if(!first) updateQuery += ", ";
                updateQuery += "avatar = '" + newInfo["avatar"].asString() + "'";
            }

            updateQuery += " WHERE username = '" + username + "';";

            // 删除旧头像
            // std::string removeQuery = "SELECT avatar FROM user_tb WHERE username = '" + username + "';";
            // auto results = dbManager.executeSelect(removeQuery);
            // std::string oldAvatar = results[0][0];
            // // LOG(DEBUG) << "旧头像: " << oldAvatar << std::endl;
            // if(!FileUtil::RemoveFile(oldAvatar)) {
            //     LOG(ERROR) << "删除旧头像失败, 更新终止: " << oldAvatar << std::endl;
            //     resp = "更新失败，删除旧头像失败";
            //     return false;
            // }

            bool success = dbManager.executeQuery(updateQuery);
            if (success) {
                resp = "更新成功";
                return true;
            } else {
                resp = dbManager.getErrorMessage();
                return false;
            }
        }

        int getUserId(const std::string &username)
        {
            std::string query = "SELECT id FROM user_tb WHERE username = '" + username + "';";
            auto results = dbManager.executeSelect(query);
            if (!results.empty() && results[0].size() >= 1) {
                return std::stoi(results[0][0]);
            }
            return -1;
        }

        void getAvatarByUsername(const std::string &username, std::string &avatarUrl)
        {
            std::string query = "SELECT avatar FROM user_tb WHERE username = '" + username + "';";
            auto results = dbManager.executeSelect(query);
            if (!results.empty() && results[0].size() >= 1) {
                avatarUrl = results[0][0];
            }
            else {
                avatarUrl = "";
            }
        }

        std::string getNameById(int id)
        {
            std::string query = "SELECT username FROM user_tb WHERE id = " + std::to_string(id) + ";";
            auto results = dbManager.executeSelect(query);
            if (!results.empty() && results[0].size() >= 1) {
                return results[0][0];
            }
            return "";
        }
    };
}
